package com.immoc.jdbc.hrapp.command;

import com.immoc.jdbc.common.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class InsertCommand implements Command{
    @Override
    public void execute() {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入员工编号");
        int eno = in.nextInt();
        System.out.println("请输入员工姓名");
        String eName = in.next();
        System.out.println("请输入员工薪资");
        float salary = in.nextFloat();
        System.out.println("请输入员工所属部门");
        String dName = in.next();
        System.out.println("请输入员工入职日期");
        String hireDate = in.next();
        Connection connection = null;
        PreparedStatement pstmt = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");
        Date udDate = null;
        try {
            udDate  = sdf.parse(hireDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        // 2.
        long time = udDate.getTime();
        java.sql.Date sdHireDate = new java.sql.Date(time);

        try {
            connection =  DbUtils.getConnection();
            String sql = "insert into employee(eno,ename,salary,dname,hireDate) values(?,?,?,?,?)";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, eno);
            pstmt.setString(2, eName);
            pstmt.setFloat(3, salary);
            pstmt.setString(4, dName);
            pstmt.setDate(5, sdHireDate);
            int cnt = pstmt.executeUpdate();
            System.out.println("cnt:"+ cnt);
            System.out.println(eName+"成功");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DbUtils.closeConnection(connection);
        }
    }
}
